﻿/**************************************************************
 *
 * 唯一标识：2c2f0ada-504a-4ef7-b257-8983c5d94a7d
 * 命名空间：Sgr.UPMS.Application.Commands.Roles
 * 创建时间：2023/8/27 17:50:46
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：角色分配功能权限命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Roles;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Roles
{
    /// <summary>
    /// 角色分配功能权限命令处理器
    /// </summary>
    public class AllocateFunctionPermissionCommandHandle : IRequestHandler<AllocateFunctionPermissionCommand, CommandResult<bool>>
    {
        public const string RoleCreate = "Sgr.UPMS.CreateRole";
        public const string RoleUpdate = "Sgr.UPMS.UpdateRole";
        public const string RoleDelete = "Sgr.UPMS.DeleteRole";
        public const string RoleView = "Sgr.UPMS.ViewRole";
        public const string RoleModifyStatus = "Sgr.UPMS.ModifyRoleStatus";
        public const string RoleAllocateFunction = "Sgr.UPMS.AllocateFunctionPermission";

        private readonly IRoleRepository _roleRepository;
        private static readonly string[] ResourcesToInclude = new string[] { "Resources" };

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roleRepository">角色仓储</param>
        public AllocateFunctionPermissionCommandHandle(IRoleRepository roleRepository)
        {
            _roleRepository = roleRepository;
        }

        /// <summary>
        /// 处理角色分配功能权限命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(AllocateFunctionPermissionCommand request, CancellationToken cancellationToken)
        {
            // 查找角色实体（包括Resources导航属性）
            var role = await _roleRepository.GetAsync(request.RoleId,
                ResourcesToInclude,
                cancellationToken);

            // 如果找不到角色，返回NotFound结果
            if (role == null)
                return CommandResult.NotFound<bool>("未找到指定的角色");

            // 更新角色的功能权限
            role.DifferenceUpdateFunctionalPermission(
                ResourceType.FunctionalPermission,
                request.FunctionPermissions);

            //如果是系统默认的超级管理员，那么需要确保其包含一下权限
            if (role.Id == Constant.SUPER_ADMIN_ROLE_ID)
            {
                role.EnsureFunctionalPermissions(
                    new string[] {
                        RoleCreate,
                        RoleUpdate,
                        RoleDelete,
                        RoleView,
                        RoleModifyStatus,
                        RoleAllocateFunction
                    });
            }

            // 更新到仓储
            await _roleRepository.UpdateAsync(role, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "角色权限更新成功");
        }
    }
}